﻿using IOA.MES.EsbApi.Models.Request.WorkOrder;
using IOA.MES.EsbApi.Models.Response;
using System.Web.Http;
using IOA.MES.Business;
using IOA.MES.EsbApi.Models.Request;
using IOA.MES.DataAccess.VModel;
using System.Collections.Generic;
using System.Linq;
using System;
using NLog;

namespace IOA.MES.EsbApi.Controllers
{
    /// <summary>
    /// 调拨管理
    /// </summary>
    public class WorkOrderController : ApiController
    {
        private Logger logger = LogManager.GetLogger(nameof(WorkOrderController));

        /// <summary>
        /// 创建工单接口
        /// </summary>
        [HttpPost]
        public BaseResponse CreateWorkOrder([FromBody] BaseRequest<List<CreateWorkOrderRequest>> request)
        {
            if (request == null || request.requestInfo == null || request.requestInfo.data == null || request.requestInfo.data.list == null)
            {
                return new BaseResponse();
            }

            var models = request.requestInfo.data.list.Select(item => new VWorkOrder
            {
                WorkshopCode = item.ScheduleGroupName,
                WorkOrderNo = item.WipEntityNumber,
                OrderNo = item.WipEntityDesc,
                ContractNo = item.Attr1,
                ProtocolNo = item.Attr3,
                ErpWorkOrderNo = item.WipEntityNumber,
                AssistUnitCode = item.UnitOfMeasure,
                ProductCode = item.AssemblyItemNumber,
                StartDate = string.IsNullOrWhiteSpace(item.StartDate) ? (DateTime?)null : Convert.ToDateTime(item.StartDate),
                EndDate = string.IsNullOrWhiteSpace(item.CompleteDate) ? (DateTime?)null : Convert.ToDateTime(item.CompleteDate),
                Count = item.Quantity,
                ProjectName = item.Attr2,
                GlassType = item.GlassType,
                WorkOrderTime = DateTime.Now,
                CreateTime = DateTime.Now,
                Boms = item.Components.Select(_ => new VWorkOrderBom
                {
                    WorkOrderNo = item.WipEntityNumber,
                    ProductCode = _.ComponentNumber,
                    Count = _.RequireQty
                }).ToList()
            }).ToList();

            try
            {
                new WorkOrderMgr().AsyncWorkOrder(models);
            }
            catch (Exception ex)
            {
                logger.Fatal(ex, $"工单同步失败，请求ID：{request.estInfo?.instId}，错误信息：{ex.Message}");
            }
            return new BaseResponse();
        }
    }
}
